﻿using System.Resources;
using System.Reflection;
using System.Collections.Generic;
using System.Collections.Concurrent;

namespace Inovout
{
    public static class StringResources
    {
        private static readonly IDictionary<StringResourceType, IDictionary<Assembly, ResourceManager>> resourceManagrDictionary =
            new ConcurrentDictionary<StringResourceType, IDictionary<Assembly, ResourceManager>>();

        static StringResources()
        {
            resourceManagrDictionary.Add(StringResourceType.Custom, new Dictionary<Assembly, ResourceManager>());
            resourceManagrDictionary.Add(StringResourceType.Alias, new Dictionary<Assembly, ResourceManager>());
            resourceManagrDictionary.Add(StringResourceType.Description, new Dictionary<Assembly, ResourceManager>());
        }

        public static string GetString(MemberInfo memberInfo, StringResourceType stringResourceType)
        {
            ResourceManager resourceManagr = null;
            if (!resourceManagrDictionary[stringResourceType].TryGetValue(memberInfo.DeclaringType.Assembly, out resourceManagr))
            {
                resourceManagr = GetResourceManagerFromAssembly(memberInfo, stringResourceType);
            }
            return resourceManagr.GetString(string.Format("{0}_{1}", memberInfo.DeclaringType.Name, memberInfo.Name));
        }
        private static readonly string[] ignoreNamespaceStrings = new string[] { ".Core.", ".Common." };
        private static ResourceManager GetResourceManagerFromAssembly(MemberInfo memberInfo, StringResourceType stringResourceType)
        {

            string baseName = null;
            if (stringResourceType == StringResourceType.Custom)
            {
                baseName = memberInfo.DeclaringType.Assembly.GetName().Name + ".Resources.StringResource";
            }
            else
            {
                baseName = memberInfo.DeclaringType.Assembly.GetName().Name + ".Resources." + stringResourceType.ToString() + "StringResource";
            }
            foreach (string ignoreNamespaceString in ignoreNamespaceStrings)
            {
                baseName = baseName.Replace(ignoreNamespaceString, ".");
            }
            ResourceManager resourceManager = new ResourceManager(baseName, memberInfo.DeclaringType.Assembly);
            resourceManagrDictionary[stringResourceType].Add(memberInfo.DeclaringType.Assembly, resourceManager);
            return resourceManager;
        }
    }
}
